package utils

import (
	"bufio"
	"io"
	"net/http"
	"os"
	"os/user"
	"path"
)

func Download(imgUrl string) (string, error) {
	DPath, err := DownloadPath()
	if err != nil {
		return "", err
	}

	fileName := path.Base(imgUrl)

	fullPath := DPath + fileName
	isExists, err := PathExists(fullPath)
	if !isExists {
		res, err := http.Get(imgUrl)
		if err != nil {
			return "", err
		}
		defer func() {
			_ = res.Body.Close()
		}()
		// 获得get请求响应的reader对象
		reader := bufio.NewReaderSize(res.Body, 32*1024)

		file, err := os.Create(fullPath)
		if err != nil {
			panic(err)
		}
		// 获得文件的writer对象
		writer := bufio.NewWriter(file)

		_, _ = io.Copy(writer, reader)
	}
	return fullPath, nil
}

func DownloadPath() (string, error) {
	userInfo, err := user.Current()
	if err != nil {
		return "", err
	}
	var dir = userInfo.HomeDir + `\Downloads\MusicGo\`
	isExists, err := PathExists(dir)
	if err != nil {
		return "", err
	}
	if !isExists {
		err = os.Mkdir(dir, 0666)
	}
	return dir, err
}
